# ModelForm实例
from django import forms
from myapp import models
from myapp.utils.encrypt import md5
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator  # 正则表达式模块
from myapp.utils.Bootstrap import BootstrapModelForm, BootstrapForm


# 用户ModelForm
class UserModelForm(BootstrapModelForm):
    name = forms.CharField(min_length=3, label='用户名')

    class Meta:
        model = models.Userinfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']
        # widgets = {
        #     'name' :forms.TextInput(attrs={'class':'form-control'}),
        #     'password' :forms.PasswordInput(attrs={'class':'form-control'}),
        #     'age' :forms.TextInput(attrs={'class':'form-control'}),
        # }


# 使用正则需导入此模块django.core.validators import RegexValidator
# 靓号ModelForm
class PretyModelform(BootstrapModelForm):
    price = forms.IntegerField(min_value=18, label='价格')

    # 方式1：正则规则判断手机号
    # mobile = forms.CharField(
    #     label='手机号',
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误')]
    # )
    class Meta:
        model = models.PretyNum
        # fields = ['mobile','price','level','status']
        fields = '__all__'  # 所有字段
        # exclude = ['level'] # 处什么字段外

    # 方式2：钩子方法
    def clean_mobile(self):
        text_mobile = self.cleaned_data["mobile"]  # 获取用户输入手机号
        exist = models.PretyNum.objects.filter(mobile=text_mobile).exists()
        if len(text_mobile) != 11:
            # 验证不通过
            raise ValidationError("格式错误")
        elif exist:
            raise ValidationError("手机号已存在")
        # 验证通过，返回用户输入的值
        return text_mobile

class PretyUpdateModelForm(BootstrapModelForm):
    mobile = forms.CharField(label="手机号") #disabled=True可设置输入框不可编辑
    class Meta:
        model = models.PretyNum
        fields = ['mobile', 'price', 'level', 'status']

    def clean_mobile(self):
        text_mobile = self.cleaned_data["mobile"]
        # exclude()排除某条件
        exist = models.PretyNum.objects.exclude(id=self.instance.pk).filter(mobile=text_mobile).exists()
        if len(text_mobile) != 11:
            # 验证不通过
            raise ValidationError("格式错误")
        elif exist:
            raise ValidationError("手机号已存在")
        # 验证通过，返回用户输入的值
        return text_mobile


# 管理员ModelForm
class AdminModeForm(BootstrapModelForm):
    confirm_pwd = forms.CharField(label='确认密码',max_length=64,widget=forms.PasswordInput(render_value=True))#render_value=True设置是否保留输入框数据
    class Meta:
        model = models.Admin
        fields = ['username','password','confirm_pwd']
        widgets = {
            'password':forms.PasswordInput(render_value=True)
        }
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    def clean_confirm_pwd(self):
        pwd = self.cleaned_data.get('password')
        cpw = md5(self.cleaned_data.get('confirm_pwd'))
        if pwd != cpw:
            raise ValidationError('密码不一致')
        return cpw

class AdminUpdateModelForm(BootstrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']

class AdminResetModeForm(BootstrapModelForm):
    confirm_pwd = forms.CharField(label='确认密码',max_length=64,widget=forms.PasswordInput())
    username = forms.CharField(label='用户名',disabled=True)
    class Meta:
        model = models.Admin
        fields = ['username','password','confirm_pwd']
        widgets = {
            'password':forms.PasswordInput(),
        }
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)
        exisit = models.Admin.objects.filter(password=md5_pwd,id=self.instance.pk).exists()#判断密码是否与原密码一致
        if exisit:
            raise ValidationError('与原密码一致')
        return md5_pwd

    def clean_confirm_pwd(self):
        pwd = self.cleaned_data.get('password')
        cpw = md5(self.cleaned_data.get('confirm_pwd'))
        if pwd != cpw:
            raise ValidationError('密码不一致')
        return cpw

# 登录Form
class LoginForm(BootstrapForm):
    username = forms.CharField(label='用户名',widget=forms.TextInput,required=True)# required=True 意思为必填项
    password = forms.CharField(label='密码',widget=forms.PasswordInput(render_value=True),required=True)#render_value的方法意思是如果密码校验不通过，也不会把输入框清空，默认情况下，PasswordInput框会清空校验不通过的密码
    code = forms.CharField(label='验证码',widget=forms.TextInput,required=True)
    def clean_password(self):
        pwd = md5(self.cleaned_data["password"]) #把输入的密码加密进行返回
        return pwd